import axios from 'axios'
import api from '~/libs/api'
import { methods, baseUrl } from '~/libs/const'

class Http {
    constructor() {
        this.last = 0
        this.lastAPI = ''
        this.baseUrl = baseUrl
    }

    fillApi(apiPath, routeParams) {
        const apiPathArr = apiPath.split('/'),
            patt = /:/

        if (!patt.test(apiPath)) {
            return apiPath
        }

        if (!routeParams || !routeParams.length) {
            console.warn(apiPath, '缺少api参数')
            return null
        }

        for (let i in apiPathArr) {
            if (patt.test(apiPathArr[i])) {
                if (!routeParams.length) {
                    console.warn(apiPath, '缺少api参数')
                    return null
                }
                apiPathArr[i] = routeParams.shift()
            }
        }

        return apiPathArr.join('/')
    }

    /**
    * 格式化参数,去除不必要的参数
    * @param {Object} params 参数
    */
    formatParams(params, method) {
        for (let i in params) {
            const item = params[i]

            if (item != 0 && !item) { // 当对象value出现null或者undefined的时候删除该item
                delete params[i]
            }

            if (Array.isArray(item) && !item.length) { // 当value为空数组的时候删除该item
                delete params[i]
            }

            if (method == methods.GET && Array.isArray(item) && item.length) {
                params[i] = params[i].join(',')
            }

            if (!!item && typeof item == 'object') {  // 如果value为一个对象递归执行该操作
                this.formatParams(item)
            }
        }
    }

    async request(apiObj, routeParams = null, params = null, isHideErrMsg = false) {

        const { path, method } = apiObj

        if (!path) {
            console.warn(apiPathOri, '无此api')
            return
        }

        const url = this.baseUrl + this.fillApi(path, routeParams)

        if (!url) {
            return
        }

        this.formatParams(params, method)

        const config = {
            method,
            url,
        }



        if (method == methods.PATCH || method == methods.POST || method == methods.PUT) {
            config.data = params
        } else {
            config.params = params
        }

        try {

            const result = await axios(config)

            const { status, data } = result

            if (status !== 200) {
                throw new Error('网络请求错误, 错误码为: ' + status)
            }

            return { data, error: null }

        } catch (err) {

            console.warn('错误码!', err);

            if (!isHideErrMsg) {
                console.warn(path, err)
            }

            return { data: null, error: err.response.data.err_msg };
        }
    }
}

export default {
  http: new Http(),
  api
}
